package com.sychip.fhc.app.drawer.screen


//import androidx.biometric.BiometricManager
//import androidx.biometric.BiometricPrompt
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.viewModelScope
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.repo.BleDeviceRepo
import com.sychip.fhc.app.data.source.dto.BleDeviceDto
import com.sychip.fhc.base.BaseAppViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.update
import timber.log.Timber
import javax.inject.Inject


/**
 * ViewModel for the Canvas screen.
 */
@HiltViewModel
class CanvasViewModel @Inject constructor(
    app : MainApplication,
    private val userRepo: BleDeviceRepo
) : BaseAppViewModel(app) {

    init {
        Timber.i("    >>>>>>>>>>>>>>>>>>>>>>>>>   StartViewModel  init   >>>>>>>>>>>>>>>>>>>>>>>>> ")
    }

    sealed interface UiTestState {
        object Null : UiTestState
        object Loading : UiTestState
        data class Success(val data: List<BleDeviceDto>) : UiTestState
        data class Error(val throwable: Throwable? = null) : UiTestState

    }


    private val _testFlow = MutableStateFlow<UiTestState>(UiTestState.Null)
    private val _testData : MutableList<BleDeviceDto>  =  mutableStateListOf<BleDeviceDto>()
    val testFlow: StateFlow<UiTestState> = _testFlow.asStateFlow()

    fun reloadTestData() {
        _testData.clear()
        _testFlow.update { UiTestState.Success( data = _testData ) }
        loadTestData()
    }

    fun loadTestData() {
        // 比下方collect写法更能处理异常
        // 还有cancel ensureActive，cancelable等写法比较实用
        userRepo.getAllBleDevices().map { result ->
            //map不是必须，我们可以在里面进行转换数据，然后 onEach....，如果不需要转换，可以移除map结构
            //UiTestState.Success(result) as UiTestState
            result
        }.onCompletion { cause ->

        }.onEach { result ->
            _testData.addAll(result)
            _testFlow.update { UiTestState.Success(data = _testData) }
        }.catch { error ->
            _testFlow.update { UiTestState.Error(error) }
        }.onStart {
            _testFlow.update { UiTestState.Loading }
        }.launchIn(viewModelScope)

    }

}


